
<?php 
include('config.php'); 
include('common-functions.php');

session_start();

$userID          = $_SESSION['userid'];
$titulo          = $_POST["Titulo"];
$artifactstype   = $_POST["artifactstype_combo"];
$texto           = $_POST["Texto"];
$tags            = $_POST["Tags"];
$uploadImage     = $_FILES["uploadimage"]['name'];
$uploadFile      = $_FILES["uploadfile"]['name'];


/******************************/
//         GLOBAL VARIABLE   
/******************************/


/******************************/
function insertDB( $titulo, $texto, $artifactstype, $userID, $file  )
{		
	$query = 'INSERT INTO tbArtifacts  (Title, Text, Type, Author, File)
    VALUES ("'.$titulo.'", "'.$texto.'", "'.$artifactstype.'", "'.$userID.'", "'.$file.'")';
	
	mysql_query("set names utf8");
	$queryResult =	mysql_query($query);
	$rowInserted = mysql_insert_id();
	
	if (!$queryResult) 
	{
		die('Invalid query: ' . mysql_error());
	}
	
	return $rowInserted;
}

function createDir($rowInserted)
{		
	// Desired folder structure
	$structure = '../storage/' . $rowInserted . '/' ;
	
	// To create the nested structure, the $recursive parameter 
	// to mkdir() must be specified.
	
	if (!mkdir($structure, 0, true)) 
	{
	    die('Failed to create folders ' . $structure . '...');
	}
	
	$imagePath = $structure . 'images/';
	if (!mkdir($imagePath, 0, true)) 
	{
	    die('Failed to create folders ' . $structure . '...');
	}
	
	$filePath = $structure . 'files/';
	if (!mkdir($filePath, 0, true)) 
	{
	    die('Failed to create folders ' . $structure . '...');
	}
	return $structure;
}

function uploadImage( $target_path, $uploadimage)
{  
	
	$target_path = $target_path . 'images/image.jpg'  ; 
	
	if(move_uploaded_file($_FILES['uploadimage']['tmp_name'], $target_path))
	{
	    echo "The file ".  basename( $uploadimage). 
	    " has been uploaded";
	} 
	else
	{
	    echo "There was an error uploading the image, please try again!";
	}
	
  return true; 
} 


function uploadFile( $target_path, $uploadfile)
{  
	$target_path = $target_path . 'files/' . basename( $uploadfile); 
	
	if(move_uploaded_file($_FILES['uploadfile']['tmp_name'], $target_path))
	{
	    echo "The file ".  basename( $uploadfile). 
	    " has been uploaded";
	} 
	else
	{
	    echo "There was an error uploading the file, please try again!";
	} 
}




if(isset($_POST['submit']))
{
	$target_path = "../storage/temp/" ;

	// Get the file name
	$file = basename( $uploadFile);
	
	// INSERT DB 
	$rowInserted = insertDB( $titulo, $texto, $artifactstype, $userID, $file  );
	
	// CREATE DIRECTORY
	$target_path = createDir($rowInserted);
	
	// IMAGE
	uploadImage( $target_path, $uploadImage );	
	
	// FILE
	uploadFile( $target_path, $uploadFile );   
	
	// Return to index page( TODO: Advise that upload was completed)
	redirect('../index.php');	
}



?>